package service

import (
	"gin-worked/app/system/model"
	"strconv"
	"time"
)

type ListApi struct {
	List  interface{}
	Total int
}

// RoleList 获取角色列表
func RoleList(limit string, offset string) Res {

	data := &model.Role{
		Status:     1,
		DeleteTime: strconv.Itoa(0),
	}

	field := []string{"id", "name", "status", "is_admin", "sort", "create_time"} //查询字段
	order := "id ASC"
	offsets, _ := strconv.Atoi(offset)
	limits, _ := strconv.Atoi(limit)

	list, err := model.RoleList(data, field, order, offsets, limits)

	if err != nil {
		return Res{0, err.Error(), ""}
	}

	total := model.RoleTotal(data)

	content := ListApi{
		List:  list,
		Total: int(total),
	}

	return Res{1, "success", content}

}

// RoleAdd 添加角色
func RoleAdd(name string, sort string, status string, is_admin string) Res {
	statusEs, _ := strconv.Atoi(status)
	sortEs, _ := strconv.Atoi(sort)
	isAdmin, _ := strconv.Atoi(is_admin)
	times := time.Now().Unix()

	content := &model.Role{
		Name:       name,
		Status:     statusEs,
		Sort:       sortEs,
		IsAdmin:    isAdmin,
		CreateTime: strconv.FormatInt(times, 10),
		UpdateTime: strconv.FormatInt(times, 10),
		DeleteTime: strconv.Itoa(0),
	}

	res, err := model.RoleAdd(content)

	if err != nil {
		return Res{0, err.Error(), ""}
	}
	return Res{1, "success", res}
}

// RoleInfo 角色详情
func RoleInfo(id string) Res {
	ids, _ := strconv.Atoi(id)

	content := &model.Role{
		Id: ids,
	}

	field := []string{"id", "name", "status", "is_admin", "sort", "create_time"} //查询字段

	res, err := model.RoleInfo(content, field)
	if err != nil {
		return Res{0, err.Error(), ""}
	}

	return Res{1, "success", res}
}

// RoleEdit 角色编辑
func RoleEdit(id string, name string, sort string, status string, is_admin string) Res {
	statusEs, _ := strconv.Atoi(status)
	sortEs, _ := strconv.Atoi(sort)
	isAdmin, _ := strconv.Atoi(is_admin)
	times := time.Now().Unix()
	var content = map[string]interface{}{"name": name, "is_admin": isAdmin, "sort": sortEs, "status": statusEs, "update_time": times}
	ids, _ := strconv.Atoi(id)
	data := &model.Role{
		Id: ids,
	}

	err := model.RoleUpdate(data, content)

	if err != nil {
		return Res{0, err.Error(), ""}
	}

	return Res{1, "success", ""}

}

// RoleDel 角色删除
func RoleDel(id string) Res {
	ids, _ := strconv.Atoi(id)
	data := &model.Role{
		Id: ids,
	}
	times := time.Now().Unix()
	var content = map[string]interface{}{"delete_time": times}
	err := model.RoleUpdate(data, content)

	if err != nil {
		return Res{0, err.Error(), ""}
	}

	return Res{1, "success", ""}
}
